package com.googlecode.allinclusive.fw.web.struts2.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.googlecode.allinclusive.fw.web.valueobject.ResultMessageObject;
import com.googlecode.allinclusive.fw.web.valueobject.UserObject;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

public class SessionInterceptor extends MethodFilterInterceptor {
	
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -2493173178702762948L;
	
	public static final String CMNI10001 = "CMNI10001";
	public static final String CMNE10001 = "CMNE10001";
	
	// "(.*)A1000W(.*),(.*)Z1000W.do(.*)"
    protected String ignoreUrl;
    
    protected String redirect = "syserr.do";
	
	public String doIntercept(ActionInvocation invocation) throws Exception {
		log.debug("session interceptor.");
		
		// Ignore?
		boolean ignore = false;
        ActionContext ac = invocation.getInvocationContext();
        HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);
        final String requestURI = request.getRequestURI();
        final String[] ignoreUrls = ignoreUrl.split(","); 
        for (String p : ignoreUrls) {
        	if (requestURI.matches(p)) {
        		ignore = true;
        		break;
        	}
        }
        if (ignore) {
        	return invocation.invoke();
        }
        
        // Login?
        HttpServletResponse response = (HttpServletResponse) ac.get(ServletActionContext.HTTP_RESPONSE);
        Map<String, Object> sess = ac.getSession();
        UserObject userObject = (UserObject) sess.get(UserObject.USER_OBJECT_KEY);
		if (userObject == null) {
			// TODO Message Code ?
			ResultMessageObject resultMessage = new ResultMessageObject(requestURI, CMNI10001, CMNE10001);
			sess.put(ResultMessageObject.RESULT_MESSAGE_KEY, resultMessage);
			response.sendRedirect(redirect);
			return null;
		} else {
			return invocation.invoke();
		}
	}
	
	public void setIgnoreUrl(String ignoreUrl) {
		this.ignoreUrl = ignoreUrl;
	}
	
	public void setRedirect(String redirect) {
		this.redirect = redirect;
	}
}